﻿<%@ Page Title="" Language="C#" MasterPageFile="~/mpTaskPanel.Master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebUI.ProjectManager.Default" Theme="Default" %>

<%@ MasterType VirtualPath="~/mpTaskPanel.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <link href="../css/smoothness/jquery-ui-1.8.7.custom.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="ProjectManager.css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="HeaderPlace" runat="server">
    <div style="text-align: center">
        כרטיס מידע<br />
        מתחמי פרוייקטים
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlace" runat="server">
    <asp:Panel ID="ContentPanel" runat="server">
        <asp:ScriptManagerProxy ID="scriptManagerProxy" runat="server">
            <Scripts>
                <asp:ScriptReference Path="~/Scripts/jquery-1.5.1.min.js" />
                <asp:ScriptReference Path="~/Scripts/jquery-ui-1.8.7.custom.min.js" />
                <asp:ScriptReference Path="~/Scripts/jquery.ui.datepicker-he.js" />
                <asp:ScriptReference Path="~/Scripts/jquery.maskedinput-1.3.min.js" />
                <asp:ScriptReference Path="~/Scripts/tools.js" />
            </Scripts>
        </asp:ScriptManagerProxy>

        <script type="text/javascript">
        var mapFrame = parent.parent.mapFrame;
        var sessionId = mapFrame.sessionId;
        var mapName = mapFrame.mapName;
        var projectId = "<%= ProjectId %>";
        var uid = <%= UID %>;
        var editMode = false;
        var project;
        var statusChanged = false;
        var statusChangedDate = "";
        var dropDownDataLoaded = 0;

        $(document).ready(function() {
            $("#ProjectManagerForm dd:even").css("background-color", "#FFFFFF");
            BindButtons();
            CreateContactsEditor();
            $("#layout").show();
            AddButtonPlaceToAll();
            CreateDatePickers(); //Moved to tools.js
            SwitchEditMode(false);
            GetDropDownData(0);
        });

        function BindButtons() {
            //Main dialog buttons
            $(".btnCancel").button().click(function() {
                LoadProject(project.ProjectId, project.UID);
                SwitchEditMode(false);
            });
            $(".btnEdit").button().click(function() {
                SwitchEditMode(true);
            });
            $(".btnSave").button().click(function() {
                SaveProject();
            });
        }

        function AddButtonPlaceToAll() {
            $("#ProjectManagerForm dd > select").each(function(i, j) { AddButtonPlace(j, 20); }); //AddButtonPlace - Moved to tools.js
            $("#ProjectManagerForm dd > input").each(function(i, j) { AddButtonPlace(j, 20); });
        }
        function SwitchEditMode(editmode) {
            editMode = editmode;
            if (editMode) {
                $(".editMode").show();
                $(".viewMode").hide();
                $("#ProjectManagerForm img").show();
            }
            else {
                $(".editMode").hide();
                $(".viewMode").show();
                $("#ProjectManagerForm img").hide();
            }
        }

        function GetDropDownData(type) {
            GetContacts(type);
            GetStatuses();
        }
        function OnDropDownDataLoaded()
        {
            if(dropDownDataLoaded == 2) LoadProject(projectId, uid);
        }
        // Project group =====================================================================
        function LoadProject(projectId, uid) {
            
            if (!projectId || !uid) return;
            $(".ajax_indicator").show();
            var data = "projectId=" + encodeURIComponent(projectId)
                     + "&uid=" + encodeURIComponent(uid);

            $.ajax({
                url: 'ProjectManagerService.asmx/GetProject',
                type: "POST",
                data: data,
                success: OnProjectLoaded,
                error: OnError
            });
        }
        function OnProjectLoaded(data) {
            project = $.parseJSON(data.text);

            $.datepicker.setDefaults($.datepicker.regional['he']);

            for (var field in project) {
                var control = $("#" + field);
                control.change(function() {
                    if (this.tagName == "SELECT") {
                        $("#v" + this.id).text($("#" + this.id + " :selected").text());
                    }
                    else {
                        if(this.id == "WorkCost") {
                            $("#v" + this.id).text(addCommas(this.value));
                        }
                        else {
                            $("#v" + this.id).text(this.value);
                        }
                    }
                });
                if (control.hasClass("datepicker")) {
                    control.datepicker("setDate", JsonDateFormat(project[field])).trigger('change'); //JsonDateFormat - moved to tools.js
                }
                else {
                    control.val(project[field]).trigger('change');
                }
            }
            GetStatusLog();
            $(".ajax_indicator").hide();
        }
        function SaveProject() {
            $(".ajax_indicator").show();

            $("#ProjectManagerForm dd > input").each(function(i, j) {
                var val = j.value;
                if ($(j).hasClass("hasDatepicker")) {
                    val = $(j).datepicker("getDate");
                    if (val != null)
                        val.setHours(12);
                    if(j.id == "StatusChangedDate" && statusChanged)
                    {
                        statusChangedDate = val;
                        return;
                    }
                }
                project[j.id] = val;
            });
            $("#ProjectManagerForm dd > select").each(function(i, j) {
                project[j.id] = j.value;
            });
            var data = "jsonString=" + encodeURIComponent(Sys.Serialization.JavaScriptSerializer.serialize(project));
            data +="&statusChangedDate=" + encodeURIComponent(Sys.Serialization.JavaScriptSerializer.serialize(statusChangedDate));
            $.ajax({
                url: 'ProjectManagerService.asmx/SaveProject',
                type: "POST",
                data: data,
                success: OnProjectSaved,
                error: OnError
            });
        }
        function OnProjectSaved(data) {
            SwitchEditMode(false);
            LoadProject(project.ProjectId, project.UID);
        }
        // End Project group =================================================================

        // Contacts group ====================================================================
        function GetContacts(type) {
            var data = "contactType=" + type;
            $.ajax({
                url: 'ProjectManagerService.asmx/GetContacts',
                type: "POST",
                data: data,
                success: OnContactsLoaded,
                error: OnError
            });
        }
        function OnContactsLoaded(data) {
            var contacts = $.parseJSON(data.text);
            $(contacts).each(function(i, j) {
                var field = GetContactField(j.TypeName);
                $("<option value='" + j.Id + "'>" + j.Name + "</option>").appendTo(field);
            });
            dropDownDataLoaded++;
            OnDropDownDataLoaded();
        }
        function GetContactField(typeName) {
            var field;
            switch (typeName) {
                case "מנהל":
                    field = "#ManagerId";
                    break;
                case "קבלן":
                    field = "#ContractorId";
                    break;
                case "מפקח":
                    field = "#InspectorId";
                    break;
                case "מתכנן":
                    field = "#PlannerId";
                    break;
            }
            return field;
        }
        // End Contacts group ================================================================

        // Statuses group ====================================================================
        function OnStatusChanged()
        {
            var statusSelect = $("#StatusId");
            if(project.StatusId != statusSelect.val())
            {
                $("#StatusChangedDate").css("background-color","#FFC3CF").datepicker("setDate", new Date());
                $(".statusChangedDate").show();
                statusChanged = true;
            }
            else
            {
                 $(".statusChangedDate").hide();
                statusChanged = false;
            }
        }
        // End Statuses group ================================================================
        
        // StatusLog group ===================================================================
        function GetStatusLog()
        {
            var data = "projectId=" + project.Id;
            $.ajax({
                url: 'ProjectManagerService.asmx/GetStatusLog',
                type: "POST",
                data: data,
                success: OnStatusLogLoaded,
                error: OnError
            });

        }
        function OnStatusLogLoaded(data)
        {
            var statusLog = $.parseJSON(data.text);
            $("#StatusLogList tr:not(.tableHeader)").remove();
            for(var i=0; i<statusLog.length; i++)
            {
                var date = JsonDateFormat(statusLog[i].Date);
                var dateString = date.getDate() + "/" + date.getMonth() + "/" + date.getFullYear();
                var cssClass = i%2==0 ? "row1" : "row2";
                var row = $("<tr>").appendTo("#StatusLogList");
                $("<td>").text(statusLog[i].Status).addClass(cssClass).appendTo(row);
                $("<td>").text(dateString).addClass(cssClass).appendTo(row);
                $("<td>").addClass(cssClass)
                         .append(statusLog[i].Comment != "" ? $("<img>").attr("src", "../Images/icon_info1.gif").click(ShowComment) : "")
                         .appendTo(row);
                         
                $("<tr>").attr("id", "CommentText"+i)
                         .addClass("commentText")
                         .addClass(cssClass)
                         .append(
                            $("<td>").attr("colspan", "3")
                                     .text(statusLog[i].Comment))
                         .appendTo("#StatusLogList")
                         .hide();
            }
        }
        function ShowComment(i)
        {
            $(".commentText").hide();
            $(i.target.parentNode.parentNode).next().show();
        }
        // End StatusLog group ===============================================================
        
        // ContactEditor functionality =======================================================
        function CreateContactsEditor() {
            $("#contactEditor").dialog({
                autoOpen: false,
                title: "הוספת איש קשר",
                width: 200,
                modal: true,
                buttons: {
                    "הוסף": SaveContact,
                    "סגור": function() { $(this).dialog("close"); }
                },
                close: function() {
                    $("#ContactName").val("").removeClass("ui-state-error");
                    $("#ContactType").val("");
                }
            });
        }
        function OpenContactEditor(contactType) {
            $("#contactEditor #ContactType").val(contactType);
            $("#contactEditor").dialog("open")
        }
        function SaveContact() {
            $("#ContactName").removeClass("ui-state-error");
            var contactName = $("#ContactName").val();
            var contactType = $("#ContactType").val();
            if (contactName.length != 0) {
                var data = "name=" + encodeURIComponent(contactName) +
                          "&type=" + encodeURIComponent(contactType);
                $.ajax({
                    url: 'ProjectManagerService.asmx/SaveContact',
                    type: "POST",
                    data: data,
                    success: OnContactSaved,
                    error: OnError
                });
            }
            else {
                $("#ContactName").addClass("ui-state-error");
            }
        }
        function OnContactSaved(data) {
            var contact = $.parseJSON(data.text);
            if (contact.Id > 0) {
                $("<option>").attr("value", contact.Id)
                             .attr("selected", "selected")
                             .text(contact.Name)
                             .appendTo(GetContactField(contact.TypeName));
            }
            $("#contactEditor").dialog("close");
        }

        function OnError(data) {
            $(".ajax_indicator").hide();
        }
        </script>

        <div id="layout" style="display: none">
            <div id="ProjectManagerForm">
                <div class="buttonsPanel viewMode" style="clear: both">
                    <input class="btnEdit" type="button" value="עריכה" />
                </div>
                <div class="buttonsPanel editMode" style="clear: both">
                    <input class="btnSave" type="button" value="אישור" />
                    <input class="btnCancel" type="button" value="ביטול" />
                </div>
                <fieldset>
                    <dl>
                        <dt>
                            <label for="Name">
                                שם הפרוייקט</label></dt>
                        <dd>
                            <input id="Name" type="text" disabled="disabled" class="editMode" />
                            <div id="vName" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="Location">
                                תיאור מיקום</label></dt>
                        <dd>
                            <input id="Location" type="text" class="editMode" />
                            <div id="vLocation" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="Nature">
                                מהות הפרוייקט</label></dt>
                        <dd>
                            <input id="Nature" type="text" class="editMode" />
                            <div id="vNature" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="StatusId">
                                סטטוס</label></dt>
                        <dd>
                            <select id="StatusId" class="editMode">
                            </select>
                            <div id="vStatusId" class="viewMode">
                            </div>
                        </dd>
                        <dt class="statusChangedDate">
                            <label for="StatusChangedDate">
                                תאריך שינוי</label></dt>
                        <dd class="statusChangedDate">
                            <input id="StatusChangedDate" class="datepicker editMode" type="text" />
                            <div id="vStatusChangedDate" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="ManagerId">
                                מנהל הפרוייקט</label></dt>
                        <dd>
                            <img src="../Images/edit.png" alt="Edit" onclick='OpenContactEditor("מנהל")' class="editMode" />
                            <select id="ManagerId" class="editMode">
                                <option value="0">בחר מרשימה</option>
                            </select>
                            <div id="vManagerId" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="ContractorId">
                                קבלן מבצע</label></dt>
                        <dd>
                            <img src="../Images/edit.png" onclick='OpenContactEditor("קבלן")' alt="Edit" class="editMode" />
                            <select id="ContractorId" class="editMode">
                                <option value="0">בחר מרשימה</option>
                            </select>
                            <div id="vContractorId" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="InspectorId">
                                מפקח</label></dt>
                        <dd>
                            <img src="../Images/edit.png" onclick='OpenContactEditor("מפקח")' alt="Edit" />
                            <select id="InspectorId" class="editMode">
                                <option value="0">בחר מרשימה</option>
                            </select>
                            <div id="vInspectorId" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="PlannerId">
                                מתכנן</label></dt>
                        <dd>
                            <img src="../Images/edit.png" onclick='OpenContactEditor("מתכנן")' alt="Edit" />
                            <select id="PlannerId" class="editMode">
                                <option value="0">בחר מרשימה</option>
                            </select>
                            <div id="vPlannerId" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="DtStart">
                                תאריך התחלה</label></dt>
                        <dd>
                            <input id="DtStart" class="datepicker editMode" type="text" />
                            <div id="vDtStart" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="DtDue">
                                סיום צפוי</label></dt>
                        <dd>
                            <input id="DtDue" class="datepicker editMode" type="text" />
                            <div id="vDtDue" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="DtEnd">
                                סיום בפועל</label></dt>
                        <dd>
                            <input id="DtEnd" class="datepicker editMode" type="text" />
                            <div id="vDtEnd" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="WorkCost">
                                עלות העבודה</label></dt>
                        <dd>
                            <input id="WorkCost" type="text" class="editMode" />
                            <div id="vWorkCost" class="viewMode">
                            </div>
                        </dd>
                        <dt>
                            <label for="Comment">
                                הערה</label></dt>
                        <dd>
                            <input id="Comment" type="text" class="editMode" />
                            <div id="vComment" class="viewMode">
                            </div>
                        </dd>
                    </dl>
                </fieldset>
                <div id="viewCommandPanel" class="buttonsPanel viewMode" style="clear: both">
                    <input class="btnEdit" type="button" value="עריכה" />
                </div>
                <div id="editCommandPanel" class="buttonsPanel editMode" style="clear: both">
                    <input class="btnSave" type="button" value="אישור" />
                    <input class="btnCancel" type="button" value="ביטול" />
                </div>
            </div>
            <div id="StatusLog">
                <div class="smallHeader">
                    אירועים:</div>
                <table id="StatusLogList">
                    <tr class="tableHeader">
                        <td>
                            סטטוס
                        </td>
                        <td>
                            תאריך
                        </td>
                        <td>
                            הערה
                        </td>
                    </tr>
                </table>
            </div>
            <div id="contactEditor">
                <dl>
                    <dt>
                        <label for="ContactName">
                            שם</label></dt>
                    <dd>
                        <input type="text" id="ContactName" /></dd>
                </dl>
                <input type="hidden" id="ContactType" />
            </div>
        </div>
        <div class="ajax_indicator">
        </div>
    </asp:Panel>
</asp:Content>
